package com.obrock;

import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.os.Bundle;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.*;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.*;
import android.widget.LinearLayout.LayoutParams;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class Main extends Activity implements GestureDetector.OnGestureListener {

    public static final String LOG_TAG = "ob-rock";
    public static final String PREFERENCES_NAME = "ob-rock-prefs";

    final int ACT_LOGIN = 1;
    final int ACT_SET_AUTH = 2;
    final int ACT_NEW_ACCOUNT = 3;
    final int ACT_EDIT_ACCOUNT = 4;
    final int ACT_NEW_TRANSFER = 5;
    final int ACT_EDIT_TRANSFER = 6;
    final int ACT_NEW_TEMPLATE = 7;
    final int ACT_NEW_PROGNOSIS = 8;
    final int ACT_PROGNOSIS_TRANSFER = 9;
    final int ACT_EDIT_PROGNOSIS = 10;
    final int ACT_EDIT_TEMPLATE = 11;

    public final static int VIEW_ACCOUNTS = 0;
    public final static int VIEW_TRANSFERS = 1;
    public final static int VIEW_DETAILS = 2;
    public final static int VIEW_TEMPLATES = 3;
    public final static int VIEW_PROGNOSIS = 4;
    public final static int VIEW_PROGNOSE = 5;
    public final static int VIEW_TEMPLATE = 6;

    public final static int SPLIT_SINGLE = 1;
    public final static int SPLIT_DOUBLE = 2;


    public static final Object tagAccount = new Object();
    public static final Object tagTransfer = new Object();
    public static final Object tagTemplate = new Object();
    public static final Object tagPrognosis = new Object();

    private static final int SWIPE_MIN_DISTANCE = 5;
    private static final int SWIPE_THRESHOLD_VELOCITY = 300;

    HorizontalScrollView root = null;
    View[] scrollItems = null;
    int currentScrollItem = 0;
    //LinearLayout screenAccounts = null;
    //LinearLayout screenPrognosis = null;
    GestureDetector gestureDetector = new GestureDetector(new MyGestureDetector());

    LinearLayout block = null;
    LinearLayout blockAccounts = null;
    LinearLayout blockPrognosis = null;
    LinearLayout blockTemplates = null;
    LinearLayout blockHeader = null;
    LinearLayout blockStatus = null;

    TextView statusMessage = null;

    public static Main context;
    public static Database db = null;

    static int screenWidth = 100;
    static int screenHeight = 100;

    public static int viewMode = VIEW_ACCOUNTS;
    public static int splitMode = SPLIT_SINGLE;
    public static Calendar[] viewPeriod = new Calendar[2];

    int widthAccounts = 100;
    int widthTransfers = 100;
    int widthDetails = 100;

    public static Account[] accounts = new Account[]{};
    //public static Balance[] transfers = new Balance[]{};
    //public static List<Prognosis> prognosis = new ArrayList<Prognosis>(0);

    Account selectedAccount = null;
    Balance selectedTransfer = null;
    Balance selectedPrognosis = null;
    Balance selectedTemplate = null;

    //Prognosis selectedPrognosis = null;
    //BackupManager mBackupManager;

    boolean loggedIn = false;
    boolean firstStart = true;
    //public Dropbox dropBox = null;
    //public MessageReceiverTask receiver = new MessageReceiverTask();


    //private static Object selectedObject = null;
    ViewHeader viewHeader = null;
    ViewAccounts viewAccounts = null;
    ViewTransfers viewTransfers = null;
    ViewDetails viewDetails = null;
    ViewPrognosis viewPrognosis = null;
    ViewDetails viewPrognose = null;
    ViewTemplates viewTemplates = null;
    ViewDetails viewTemplate = null;

    private GestureDetector gDetector;

    public Main() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;


        if (firstStart) {
            db = new Database(this);
            viewPeriod = getPeriod(Calendar.MONTH, Calendar.getInstance(TimeZone.getDefault()));
            viewPeriod[1].add(Calendar.DAY_OF_MONTH, getSharedPreferences(Main.PREFERENCES_NAME, 0).getInt("PROGNOSIS_DAYS_AFTER", 10));
            //dropBox = new Dropbox(this);

        }

        if (!loggedIn && db.getParamString("login") != null) {
            Intent i = new Intent(this, EditAuthentication.class);
            i.putExtra("window_title", getResources().getString(R.string.prompt_login));
            startActivityForResult(i, ACT_LOGIN);
        } else {
            show();
            //dropBox.login();

            //if (!loggedIn) {
            //   loggedIn = true;

            //mBackupManager = new BackupManager(this);
            //mBackupManager.dataChanged();

            //dropBox.login(context);

            /*
            mBackupManager.requestRestore(new RestoreObserver() {
                AlertDialog message = null;
                int cnt = 0;

                @Override
                public void restoreStarting(int numPackages) {
                    cnt = numPackages;
                    message = new AlertDialog.Builder(context).create();
                    message.setTitle(getResources().getString(R.string.msg_sync));
                    message.setMessage(getResources().getString(R.string.msg_sync_packets, cnt));
                    message.show();
                }

                @Override
                public void onUpdateComplex(int nowBeingRestored, String currentPackage) {
                    if (message != null) {
                        message.setMessage(getResources().getString(R.string.msg_sync_packet,
                                String.format("%d/%d", nowBeingRestored+1, cnt)));
                    }
                }

                @Override
                public void restoreFinished(int error) {
                    int i = error;
                    message.hide();
                    refreshView();
                }
            });
            */

            // }
            //}

            //getActionBar().setDisplayHomeAsUpEnabled(true);
            //getActionBar().setDisplayShowHomeEnabled(false);

            //dropBox.enable();
            //Dropbox.force();

        }

        //MessageTemplate t = new MessageTemplate("Karta MasterCard *%KEY%.Spisanie so scheta: -%AMOUNT% %CURRENCY% %TITLE% %DATE=dd.MM.yyyy HH:mm%. Dostupno: %BALANCE% %CURRENCY%. Bank Russkiy Standart");
        //t.parse("Karta MasterCard *6963.Spisanie so scheta: -300.00 RUB 20002666>TELE2 08.10.2012 18:47. Dostupno: 5878.20 RUB. Bank Russkiy Standart");

    }

    void show() {
        setContentView(R.layout.main);
        gDetector = new GestureDetector(this);

        Point p = new Point();
        getWindowManager().getDefaultDisplay().getSize(p);
        screenWidth = p.x;
        screenHeight = p.y;

        if (screenWidth > screenHeight) {
            splitMode = SPLIT_DOUBLE;
        } else {
            splitMode = SPLIT_SINGLE;
        }

        blockHeader = (LinearLayout) findViewById(R.id.block_header);
        blockPrognosis = (LinearLayout) findViewById(R.id.block_prognosis);
        blockAccounts = (LinearLayout) findViewById(R.id.block_accounts);
        blockTemplates = (LinearLayout) findViewById(R.id.block_templates);
        blockStatus = (LinearLayout) findViewById(R.id.block_status);

        statusMessage = (TextView) findViewById(R.id.status_message);
        blockStatus.setVisibility(View.GONE);


        if (firstStart) {
            viewHeader = new ViewHeader(context);
            viewAccounts = new ViewAccounts(null, context);
            viewTransfers = new ViewTransfers(null, null, context);
            viewDetails = new ViewDetails(null, context);
            viewPrognosis = new ViewPrognosis(viewPeriod, context);
            viewPrognose = new ViewDetails(null, context);
            viewTemplates = new ViewTemplates(context);
            viewTemplate = new ViewDetails(null, context);

            blockHeader.addView(viewHeader);

            blockAccounts.addView(viewAccounts);
            blockAccounts.addView(viewTransfers);
            blockAccounts.addView(viewDetails);

            blockPrognosis.addView(viewPrognosis);
            blockPrognosis.addView(viewPrognose);

            blockTemplates.addView(viewTemplates);
            blockTemplates.addView(viewTemplate);

            blockPrognosis.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    //If the user swipes
                    //if (gestureDetector.onTouchEvent(event)) {
                    //    return true;
                    /*} else*/
                    if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
                        int scrollX = viewPrognosis.getScrollX();
                        int featureWidth = v.getMeasuredWidth();
                        currentScrollItem = ((scrollX + (featureWidth / 2)) / featureWidth);
                        int scrollTo = currentScrollItem * featureWidth;
                        //root.smoothScrollTo(scrollTo, 0);
                        return true;
                    } else {
                        return false;
                    }
                }
            });


            /*
            switch (splitMode) {
                case SPLIT_DOUBLE:
                    viewMode = VIEW_ACCOUNTS;
                    context.viewAccounts.setVisibility(View.VISIBLE);
                    context.viewTransfers.setVisibility(View.VISIBLE);
                    context.viewDetails.setVisibility(View.GONE);
                    context.viewTransfers.setLayoutParams(new LayoutParams(point.x * 40 / 100, LayoutParams.MATCH_PARENT));
                    context.viewDetails.setLayoutParams(new LayoutParams(point.x * 60 / 100, LayoutParams.MATCH_PARENT));
                    break;
                case SPLIT_SINGLE:
                    viewMode = VIEW_ACCOUNTS;
                    context.viewAccounts.setVisibility(View.VISIBLE);
                    context.viewTransfers.setVisibility(View.GONE);
                    context.viewDetails.setVisibility(View.GONE);
                    context.viewAccounts.setLayoutParams(new LayoutParams(point.x, LayoutParams.MATCH_PARENT));
                    break;
            }
            */

            //refreshView();

            /*
            Calendar now = Calendar.getInstance(TimeZone.getDefault());
            Calendar[] d1 = getPeriod(Calendar.MONTH, now);
            d1[1].add(Calendar.DAY_OF_MONTH, 7);

            now.add(Calendar.MONTH, -1);
            Calendar[] d0 = getPeriod(Calendar.MONTH, now);
            d0[1].add(Calendar.DAY_OF_MONTH, 7);

            now.add(Calendar.MONTH, 2);
            Calendar[] d2 = getPeriod(Calendar.MONTH, now);
            d2[1].add(Calendar.DAY_OF_MONTH, 7);

            scrollItems = new View[]{
                    new ViewPrognosis(d0, context),
                    new ViewPrognosis(d1, context),
                    new ViewPrognosis(d2, context)
            };
            currentScrollItem = 1;

            root = (HorizontalScrollView) findViewById(R.id.prognosis_root);

            root.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    //If the user swipes
                    if (gestureDetector.onTouchEvent(event)) {
                        return true;
                    } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
                        int scrollX = root.getScrollX();
                        int featureWidth = v.getMeasuredWidth();
                        currentScrollItem = ((scrollX + (featureWidth / 2)) / featureWidth);
                        int scrollTo = currentScrollItem * featureWidth;
                        root.smoothScrollTo(scrollTo, 0);
                        return true;
                    } else {
                        return false;
                    }
                }
            });
            */


            /*
            mBackupManager.requestRestore(new RestoreObserver() {
                @Override
                public void restoreStarting(int numPackages) {
                    int i = numPackages;
                }

                @Override
                public void onUpdateComplex(int nowBeingRestored, String currentPackage) {
                    int i = nowBeingRestored;
                }

                @Override
                public void restoreFinished(int error) {
                    int i = error;
                    refreshView();
                }
            });
            */


            //refreshView();
            //mBackupManager.dataChanged();

            //refreshAccounts();

            /*
            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
            TextView title = (TextView) findViewById(R.id.title_string);
            ImageView icon  = (ImageView) findViewById(R.id.title_icon);
            icon.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    onBackPressed();
                }
            });
            */

            viewHeader.actionIcon.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    Intent intent = new Intent(context, EditBalance.class);
                    startActivityForResult(intent, ACT_NEW_TRANSFER);
                    return true;
                }
            });

            viewHeader.syncIcon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (context.blockStatus.getVisibility() == View.VISIBLE) {
                        context.blockStatus.setVisibility(View.GONE);
                    } else {
                        context.blockStatus.setVisibility(View.VISIBLE);
                    }
                }
            });

            blockStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    context.blockStatus.setVisibility(View.GONE);
                }
            });

            if (firstStart) {
                startService(new Intent(context, SyncService.class));
                firstStart = false;
            }

            setMode(viewMode);
        }

        //MessageThread.force();

        MessageThread.force();
        DropboxThread.force();

    }

    /*
    private String[] getAccountNames() {
        mAccountManager = AccountManager.get(this);
        Account[] accounts = mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
        String[] names = new String[accounts.length];
        for (int i = 0; i < names.length; i++) {
            names[i] = accounts[i].name;
        }
        return names;
    }
    */


    public static void setObject(int mode, Object selected) {
        switch (mode) {
            case VIEW_ACCOUNTS:
                context.selectedAccount = (Account) selected;
                break;
            case VIEW_TRANSFERS:
                context.selectedTransfer = (Balance) selected;
                break;
            case VIEW_PROGNOSIS:
                context.selectedPrognosis = (Balance) selected;
                break;
            case VIEW_TEMPLATES:
                context.selectedTemplate = (Balance) selected;
                break;
        }
    }


    public static void refreshHeader() {
        if (context == null) return;

        switch (viewMode) {
            case VIEW_ACCOUNTS:
                if (context.viewAccounts != null) {
                    double[] balance = context.viewAccounts.getBalance();
                    context.viewHeader.set(
                            context.getResources().getDrawable(R.drawable.bag),
                            context.getResources().getDrawable(R.drawable.clipboard),
                            context.getResources().getText(R.string.prompt_accounts).toString(),
                            balance[0], balance[1], balance[2]);
                    context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            context.doMenuAction(R.id.create_transfer);
                        }
                    });
                }
                break;

            case VIEW_TRANSFERS:
                if (context.viewTransfers != null) {
                    context.viewHeader.set(
                            context.viewTransfers.getImage(),
                            context.getResources().getDrawable(R.drawable.clipboard),
                            context.selectedAccount.name,
                            String.format(context.getResources().getString(R.string.account_balance),
                                    context.selectedAccount.balance));
                    context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            context.doMenuAction(R.id.create_transfer);
                        }
                    });
                }
                break;

            case VIEW_DETAILS:
                if (context.viewTransfers != null) {
                    context.viewHeader.set(
                            context.viewTransfers.getImage(),
                            context.getResources().getDrawable(R.drawable.pencil),
                            context.selectedAccount.name,
                            String.format(context.getResources().getString(R.string.account_balance),
                                    context.selectedAccount.balance));
                    context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            context.doMenuAction(R.id.edit_transfer);
                        }
                    });
                }
                break;

            case VIEW_PROGNOSIS:
                if (context.viewPrognosis != null) {
                    context.viewHeader.set(context.getResources().getDrawable(R.drawable.transfer),
                            context.getResources().getDrawable(R.drawable.clipboard),
                            String.format("%s %tY",
                                    context.getResources().getTextArray(R.array.months)[context.viewPrognosis.viewPeriod[0].get(Calendar.MONTH)],
                                    context.viewPrognosis.viewPeriod[0]),
                            String.format(context.getResources().getString(R.string.prompt_payment_rest), context.viewPrognosis.balanceCredit),
                            String.format(context.getResources().getString(R.string.prompt_payment_payed), context.viewPrognosis.balanceDebt));
                    context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            context.doMenuAction(R.id.create_prognosis);
                        }
                    });
                }
                break;

            case VIEW_PROGNOSE:
                if (context.viewPrognosis != null) {
                    context.viewHeader.set(context.getResources().getDrawable(R.drawable.transfer),
                            context.getResources().getDrawable(R.drawable.pencil),
                            String.format("%tB %tY", context.viewPrognosis.viewPeriod[0], context.viewPrognosis.viewPeriod[0]),
                            String.format(context.getResources().getString(R.string.prompt_payment_rest), context.viewPrognosis.balanceCredit),
                            String.format(context.getResources().getString(R.string.prompt_payment_payed), context.viewPrognosis.balanceDebt));
                    context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            context.doMenuAction(R.id.edit_prognosis);
                        }
                    });
                }
                break;

            case VIEW_TEMPLATES:
                context.viewHeader.set(context.getResources().getDrawable(R.drawable.bubble),
                        context.getResources().getDrawable(R.drawable.clipboard),
                        context.getResources().getString(R.string.menu_templates));
                context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        context.doMenuAction(R.id.create_template);
                    }
                });
                break;

            case VIEW_TEMPLATE:
                context.viewHeader.set(context.getResources().getDrawable(R.drawable.bubble),
                        context.getResources().getDrawable(R.drawable.pencil),
                        context.getResources().getString(R.string.menu_templates));
                context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        context.doMenuAction(R.id.edit_template);
                    }
                });
                break;
        }
    }


    public static void setMode(int mode) {

        if (screenWidth > screenHeight) {
            splitMode = SPLIT_DOUBLE;
            switch (viewMode) {
                case VIEW_DETAILS:
                    viewMode = VIEW_TRANSFERS;
                    break;
                case VIEW_TEMPLATE:
                    viewMode = VIEW_TEMPLATES;
                    break;
                case VIEW_PROGNOSE:
                    viewMode = VIEW_PROGNOSIS;
                    break;
            }
        } else {
            splitMode = SPLIT_SINGLE;
        }


        viewMode = mode;
        switch (mode) {
            case VIEW_ACCOUNTS:
                setPage(VIEW_ACCOUNTS);
                switch (splitMode) {
                    case SPLIT_DOUBLE:
                        context.viewAccounts.setVisibility(View.VISIBLE);
                        context.viewTransfers.setVisibility(View.VISIBLE);
                        context.viewDetails.setVisibility(View.GONE);
                        context.viewAccounts.setLayoutParams(new LayoutParams(screenWidth * 40 / 100, LayoutParams.MATCH_PARENT));
                        context.viewTransfers.setLayoutParams(new LayoutParams(screenWidth * 60 / 100, LayoutParams.MATCH_PARENT));
                        context.selectedAccount = context.viewAccounts.refresh(context.selectedAccount);
                        context.viewTransfers.refresh(context.selectedAccount,
                                context.selectedTransfer,
                                context.getResources().getColor(R.color.pane_color));
                        break;
                    case SPLIT_SINGLE:
                        context.viewAccounts.setVisibility(View.VISIBLE);
                        context.viewTransfers.setVisibility(View.GONE);
                        context.viewDetails.setVisibility(View.GONE);
                        context.viewAccounts.setLayoutParams(new LayoutParams(screenWidth, LayoutParams.MATCH_PARENT));
                        context.selectedAccount = context.viewAccounts.refresh(context.selectedAccount);
                        break;
                }
                /*
                double[] balance = context.viewAccounts.getBalance();
                context.viewHeader.set(
                        context.getResources().getDrawable(R.drawable.bag),
                        context.getResources().getDrawable(R.drawable.plus),
                        context.getResources().getText(R.string.prompt_accounts).toString(),
                        balance[0], balance[1], balance[2]);
                context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        context.doMenuAction(R.id.create_transfer);
                    }
                });
                */
                break;

            case VIEW_TRANSFERS:
                setPage(VIEW_ACCOUNTS);
                switch (splitMode) {
                    case SPLIT_DOUBLE:
                        context.viewAccounts.setVisibility(View.GONE);
                        context.viewTransfers.setVisibility(View.VISIBLE);
                        context.viewDetails.setVisibility(View.VISIBLE);
                        context.viewTransfers.setLayoutParams(new LayoutParams(screenWidth * 40 / 100, LayoutParams.MATCH_PARENT));
                        context.viewDetails.setLayoutParams(new LayoutParams(screenWidth * 60 / 100, LayoutParams.MATCH_PARENT));
                        context.selectedTransfer = context.viewTransfers.refresh(context.selectedAccount,
                                context.selectedTransfer,
                                context.getResources().getColor(R.color.background_color));
                        context.viewDetails.refresh(context.selectedTransfer);
                        break;
                    case SPLIT_SINGLE:
                        context.viewAccounts.setVisibility(View.GONE);
                        context.viewTransfers.setVisibility(View.VISIBLE);
                        context.viewDetails.setVisibility(View.GONE);
                        context.viewTransfers.setLayoutParams(new LayoutParams(screenWidth, LayoutParams.MATCH_PARENT));
                        context.selectedTransfer = context.viewTransfers.refresh(context.selectedAccount,
                                context.selectedTransfer,
                                context.getResources().getColor(R.color.background_color));
                        break;
                }
                /*
                context.viewHeader.set(
                        context.viewTransfers.getImage(),
                        context.getResources().getDrawable(R.drawable.plus),
                        context.selectedAccount.name,
                        String.format(context.getResources().getString(R.string.account_balance),
                                context.selectedAccount.balance));
                context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        context.doMenuAction(R.id.create_transfer);
                    }
                });
                */
                break;


            case VIEW_DETAILS:
                setPage(VIEW_ACCOUNTS);
                switch (splitMode) {
                    case SPLIT_DOUBLE:
                        break;
                    case SPLIT_SINGLE:
                        context.viewAccounts.setVisibility(View.GONE);
                        context.viewTransfers.setVisibility(View.GONE);
                        context.viewDetails.setVisibility(View.VISIBLE);
                        context.viewDetails.setLayoutParams(new LayoutParams(screenWidth, LayoutParams.MATCH_PARENT));
                        context.viewDetails.refresh(context.selectedTransfer);
                        break;
                }
                /*
                context.viewHeader.set(
                        context.viewTransfers.getImage(),
                        context.getResources().getDrawable(R.drawable.pencil),
                        context.selectedAccount.name,
                        String.format(context.getResources().getString(R.string.account_balance),
                                context.selectedAccount.balance));
                context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        context.doMenuAction(R.id.edit_transfer);
                    }
                });
                */
                break;

            case VIEW_PROGNOSIS:
                setPage(VIEW_PROGNOSIS);
                switch (splitMode) {
                    case SPLIT_DOUBLE:
                        context.viewPrognosis.setVisibility(View.VISIBLE);
                        context.viewPrognose.setVisibility(View.VISIBLE);
                        context.viewPrognosis.setLayoutParams(new LayoutParams(screenWidth * 40 / 100, LayoutParams.MATCH_PARENT));
                        context.viewPrognose.setLayoutParams(new LayoutParams(screenWidth * 60 / 100, LayoutParams.MATCH_PARENT));
                        context.selectedPrognosis = context.viewPrognosis.refresh();
                        context.viewPrognose.refresh(context.selectedPrognosis);
                        break;
                    case SPLIT_SINGLE:
                        context.viewPrognosis.setVisibility(View.VISIBLE);
                        context.viewPrognose.setVisibility(View.GONE);
                        context.viewPrognosis.setLayoutParams(new LayoutParams(screenWidth, LayoutParams.MATCH_PARENT));
                        context.selectedPrognosis = context.viewPrognosis.refresh();
                        break;
                }
                /*
                context.viewHeader.set(context.getResources().getDrawable(R.drawable.transfer),
                        context.getResources().getDrawable(R.drawable.plus),
                        String.format("%s %tY",
                                context.getResources().getTextArray(R.array.months)[context.viewPrognosis.viewPeriod[0].get(Calendar.MONTH)],
                                context.viewPrognosis.viewPeriod[0]),
                        String.format(context.getResources().getString(R.string.prompt_payment_rest), context.viewPrognosis.balanceCredit),
                        String.format(context.getResources().getString(R.string.prompt_payment_payed), context.viewPrognosis.balanceDebt));
                context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        context.doMenuAction(R.id.create_prognosis);
                    }
                });
                */
                break;

            case VIEW_PROGNOSE:
                setPage(VIEW_PROGNOSIS);
                switch (splitMode) {
                    case SPLIT_DOUBLE:
                        break;
                    case SPLIT_SINGLE:
                        context.viewPrognosis.setVisibility(View.GONE);
                        context.viewPrognose.setVisibility(View.VISIBLE);
                        context.viewPrognose.setLayoutParams(new LayoutParams(screenWidth, LayoutParams.MATCH_PARENT));
                        context.viewPrognose.refresh(context.selectedPrognosis);
                        break;
                }
                /*
                context.viewHeader.set(context.getResources().getDrawable(R.drawable.transfer),
                        context.getResources().getDrawable(R.drawable.pencil),
                        String.format("%tB %tY", context.viewPrognosis.viewPeriod[0], context.viewPrognosis.viewPeriod[0]),
                        String.format(context.getResources().getString(R.string.prompt_payment_rest), context.viewPrognosis.balanceCredit),
                        String.format(context.getResources().getString(R.string.prompt_payment_payed), context.viewPrognosis.balanceDebt));
                context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        context.doMenuAction(R.id.edit_prognosis);
                    }
                });
                */
                break;

            case VIEW_TEMPLATES:
                setPage(VIEW_TEMPLATES);
                switch (splitMode) {
                    case SPLIT_DOUBLE:
                        context.viewTemplates.setVisibility(View.VISIBLE);
                        context.viewTemplate.setVisibility(View.VISIBLE);
                        context.viewTemplates.setLayoutParams(new LayoutParams(screenWidth * 40 / 100, LayoutParams.MATCH_PARENT));
                        context.viewTemplate.setLayoutParams(new LayoutParams(screenWidth * 60 / 100, LayoutParams.MATCH_PARENT));
                        context.selectedTemplate = context.viewTemplates.refresh();
                        context.viewTemplate.refresh(context.selectedTemplate);
                        break;
                    case SPLIT_SINGLE:
                        context.viewTemplates.setVisibility(View.VISIBLE);
                        context.viewTemplate.setVisibility(View.GONE);
                        context.viewPrognosis.setLayoutParams(new LayoutParams(screenWidth, LayoutParams.MATCH_PARENT));
                        context.selectedTemplate = context.viewPrognosis.refresh();
                        break;
                }
                /*
                context.viewHeader.set(context.getResources().getDrawable(R.drawable.bubble),
                        context.getResources().getDrawable(R.drawable.plus),
                        context.getResources().getString(R.string.menu_templates));
                context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        context.doMenuAction(R.id.create_template);
                    }
                });
                */
                break;

            case VIEW_TEMPLATE:
                setPage(VIEW_TEMPLATES);
                switch (splitMode) {
                    case SPLIT_DOUBLE:
                        break;
                    case SPLIT_SINGLE:
                        context.viewTemplates.setVisibility(View.GONE);
                        context.viewTemplate.setVisibility(View.VISIBLE);
                        context.viewTemplate.setLayoutParams(new LayoutParams(screenWidth, LayoutParams.MATCH_PARENT));
                        context.viewTemplate.refresh(context.selectedTemplate);
                        break;
                }
                /*
                context.viewHeader.set(context.getResources().getDrawable(R.drawable.bubble),
                        context.getResources().getDrawable(R.drawable.pencil),
                        context.getResources().getString(R.string.menu_templates));
                context.viewHeader.actionIcon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        context.doMenuAction(R.id.edit_template);
                    }
                });
                */
                break;
        }

        refreshHeader();
    }

    public static void doAction(int mode, Object selected) {

        switch (mode) {
            case VIEW_ACCOUNTS:
                context.selectedAccount = (Account) selected;
                switch (splitMode) {
                    case SPLIT_DOUBLE:
                        if (viewMode == VIEW_ACCOUNTS) {
                            context.viewTransfers.refresh(context.selectedAccount,
                                    context.selectedTransfer,
                                    context.getResources().getColor(R.color.pane_color));
                            //refreshHeader();
                        } else {
                            setMode(VIEW_ACCOUNTS);
                        }
                        break;
                    case SPLIT_SINGLE:
                        setMode(VIEW_TRANSFERS);
                        break;
                }
                break;

            case VIEW_TRANSFERS:
                context.selectedTransfer = (Balance) selected;
                switch (splitMode) {
                    case SPLIT_DOUBLE:
                        if (viewMode == VIEW_TRANSFERS) {
                            context.viewDetails.refresh(context.selectedTransfer);
                            //refreshHeader();
                        } else {
                            setMode(VIEW_TRANSFERS);
                        }
                        break;
                    case SPLIT_SINGLE:
                        setMode(VIEW_DETAILS);
                        break;
                }
                break;

            case VIEW_PROGNOSIS:
                context.selectedPrognosis = (Balance) selected;
                switch (splitMode) {
                    case SPLIT_DOUBLE:
                        if (viewMode == VIEW_PROGNOSIS) {
                            context.viewPrognose.refresh(context.selectedPrognosis);
                        } else {
                            setMode(VIEW_PROGNOSIS);
                        }
                        break;
                    case SPLIT_SINGLE:
                        setMode(VIEW_PROGNOSE);
                        break;
                }
                break;

            case VIEW_TEMPLATES:
                context.selectedTemplate = (Balance) selected;
                switch (splitMode) {
                    case SPLIT_DOUBLE:
                        if (viewMode == VIEW_TEMPLATES) {
                            context.viewTemplate.refresh(context.selectedTemplate);
                        } else {
                            setMode(VIEW_TEMPLATES);
                        }
                        break;
                    case SPLIT_SINGLE:
                        setMode(VIEW_TEMPLATE);
                        break;
                }
                break;

        }
    }

    @Override
    public void onBackPressed() {

        switch (viewMode) {
            case VIEW_ACCOUNTS:
                setMode(VIEW_PROGNOSIS);
                break;

            case VIEW_TRANSFERS:
                setMode(VIEW_ACCOUNTS);
                break;

            case VIEW_DETAILS:
                setMode(VIEW_TRANSFERS);
                break;

            case VIEW_PROGNOSIS:
                setMode(VIEW_ACCOUNTS);
                break;

            case VIEW_PROGNOSE:
                setMode(VIEW_PROGNOSIS);
                break;

            case VIEW_TEMPLATES:
                setMode(VIEW_ACCOUNTS);
                startActivity(new Intent(this, Settings.class));
                break;

            case VIEW_TEMPLATE:
                setMode(VIEW_TEMPLATES);
                break;


        }
        //refreshView();

    }


    static void setPage(int page) {

        switch (page) {
            case VIEW_ACCOUNTS:
                context.blockPrognosis.setVisibility(View.GONE);
                context.blockAccounts.setVisibility(View.VISIBLE);
                context.blockTemplates.setVisibility(View.GONE);
                context.blockAccounts.setLayoutParams(new LayoutParams(screenWidth, LayoutParams.MATCH_PARENT));
                //setMode(VIEW_ACCOUNTS);
                break;

            case VIEW_PROGNOSIS:
                context.blockPrognosis.setVisibility(View.VISIBLE);
                context.blockAccounts.setVisibility(View.GONE);
                context.blockTemplates.setVisibility(View.GONE);
                context.blockPrognosis.setLayoutParams(new LayoutParams(screenWidth, LayoutParams.MATCH_PARENT));
                //setMode(VIEW_PROGNOSIS);
                break;

            case VIEW_TEMPLATES:
                context.blockPrognosis.setVisibility(View.GONE);
                context.blockAccounts.setVisibility(View.GONE);
                context.blockTemplates.setVisibility(View.VISIBLE);
                context.blockTemplates.setLayoutParams(new LayoutParams(screenWidth, LayoutParams.MATCH_PARENT));
                //setMode(VIEW_TEMPLATES);
                break;
        }

        refreshHeader();

    }


    /*
    public static void dataChanged() {
        DropboxThread.dataChanged();
    }
    */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }

        switch (requestCode) {
            case ACT_SET_AUTH:
                if (resultCode == RESULT_OK) {
                    String login = data.getStringExtra("login");
                    String password = data.getStringExtra("password");

                    db.setParam("login", login);
                    db.setParam("password", password);
                    toast(getResources().getString(R.string.msg_chlogin));
                }
                break;

            case ACT_LOGIN:
                if (resultCode == RESULT_OK) {
                    String login = data.getStringExtra("login");
                    String password = data.getStringExtra("password");

                    if (!login.equals(db.getParamString("login"))
                            || !password.equals(db.getParamString("password"))) {

                        Intent i = new Intent(this, EditAuthentication.class);
                        i.putExtra("window_title", getResources().getString(R.string.prompt_login));
                        startActivityForResult(i, ACT_LOGIN);

                        toast(getResources().getString(R.string.msg_invalid_password));

                    } else {
                        loggedIn = true;
                    }

                    show();

                    /*
                    setContentView(R.layout.main);
                    root = (HorizontalScrollView) findViewById(R.id.root);
                    screenAccounts = (LinearLayout) findViewById(R.id.screen_accounts);
                    screenPrognosis = (LinearLayout) findViewById(R.id.screen_prognosis);
                    scrollItems = new View[]{screenAccounts, screenPrognosis};
                    root.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            //If the user swipes
                            if (gestureDetector.onTouchEvent(event)) {
                                return true;
                            } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
                                int scrollX = root.getScrollX();
                                int featureWidth = v.getMeasuredWidth();
                                currentScrollItem = ((scrollX + (featureWidth / 2)) / featureWidth);
                                int scrollTo = currentScrollItem * featureWidth;
                                root.smoothScrollTo(scrollTo, 0);
                                return true;
                            } else {
                                return false;
                            }
                        }
                    });


                    refreshView();
                    //refreshAccounts();
                    */

                } else {
                    finish();
                }
                break;

            case ACT_NEW_ACCOUNT:
                if (resultCode == RESULT_OK) {
                    selectedAccount = (Account) data.getSerializableExtra("account");
                    selectedAccount.append();
                    toast(getResources().getString(R.string.msg_account_added) + ": " + selectedAccount.name);
                    viewAccounts.refresh(selectedAccount);
                    refreshHeader();
                }
                break;

            case ACT_EDIT_ACCOUNT:
                if (resultCode == RESULT_OK) {
                    selectedAccount = (Account) data.getSerializableExtra("account");
                    selectedAccount.update();
                    toast(getResources().getString(R.string.msg_account_updated)
                            + ": "
                            + selectedAccount.name);
                    viewAccounts.refresh(selectedAccount);
                    refreshHeader();
                }
                break;

            case ACT_NEW_PROGNOSIS:
                if (resultCode == RESULT_OK) {
                    selectedPrognosis = (Balance) data.getSerializableExtra("balance");
                    selectedPrognosis.append();
                    toast(getResources().getString(R.string.msg_prognosis_added) + ": " + selectedPrognosis.name);
                    viewPrognosis.refresh();
                    refreshHeader();
                }
                break;

            case ACT_NEW_TEMPLATE:
                if (resultCode == RESULT_OK) {
                    selectedTemplate = (Balance) data.getSerializableExtra("balance");
                    selectedTemplate.append();
                    toast(getResources().getString(R.string.msg_template_added) + ": " + selectedTemplate.name);
                    viewTemplates.refresh();
                    refreshHeader();
                }
                break;

            case ACT_NEW_TRANSFER:
                if (resultCode == RESULT_OK) {
                    selectedTransfer = (Balance) data.getSerializableExtra("balance");
                    selectedTransfer.append();
                    toast(getResources().getString(R.string.msg_transfer_added) + ": " + selectedTransfer.name);
                    viewTransfers.refresh(selectedTransfer);
                    refreshHeader();
                }
                break;

            case ACT_EDIT_PROGNOSIS:
                if (resultCode == RESULT_OK) {
                    selectedPrognosis = (Balance) data.getSerializableExtra("balance");
                    selectedPrognosis.update();
                    toast(getResources().getString(R.string.msg_prognosis_changes) + ": " + selectedPrognosis.name);
                    viewPrognosis.refresh();
                    viewPrognose.refresh(selectedPrognosis);
                    refreshHeader();
                }
                break;

            case ACT_EDIT_TEMPLATE:
                if (resultCode == RESULT_OK) {
                    selectedTemplate = (Balance) data.getSerializableExtra("balance");
                    selectedTemplate.update();
                    toast(getResources().getString(R.string.msg_template_changes) + ": " + selectedTemplate.name);
                    viewTemplates.refresh();
                    viewTemplate.refresh(selectedTemplate);
                    refreshHeader();
                }
                break;

            case ACT_EDIT_TRANSFER:
                if (resultCode == RESULT_OK) {
                    selectedTransfer = (Balance) data.getSerializableExtra("balance");
                    selectedTransfer.update();
                    toast(getResources().getString(R.string.msg_transfer_changes) + ": " + selectedTransfer.name);
                    viewTransfers.refresh(selectedTransfer);
                    viewDetails.refresh(selectedTransfer);
                    refreshHeader();
                }
                break;


            case ACT_PROGNOSIS_TRANSFER:
                if (resultCode == RESULT_OK) {
                    selectedPrognosis = (Balance) data.getSerializableExtra("balance");
                    selectedPrognosis.mode = Balance.MODE_NORMAL;
                    selectedPrognosis.append();
                    viewPrognosis.refresh();
                    viewPrognose.refresh(selectedPrognosis);
                    refreshHeader();
                    toast(getResources().getString(R.string.msg_prognosis_transfered) + ": " + selectedPrognosis.name);
                }
                break;


        }
    }


    Boolean doMenuAction(int id) {
        Intent intent;
        switch (id) {

            case R.id.create_account:
                createAccount();
                return true;
            case R.id.create_transfer:
                createTransfer();
                return true;
            case R.id.create_prognosis:
                createPrognosis(null);
                return true;
            case R.id.create_template:
                createTemplate();
                return true;

            case R.id.edit_account:
                editAccount(false);
                return true;
            case R.id.edit_transfer:
                editTransfer(false);
                return true;
            case R.id.edit_prognosis:
                editPrognosis(false);
                return true;
            case R.id.edit_template:
                editTemplate(false);
                return true;

            case R.id.duplicate_account:
                editAccount(true);
                return true;
            case R.id.duplicate_transfer:
                editTransfer(true);
                return true;
            case R.id.duplicate_prognosis:
                editPrognosis(true);
                return true;
            case R.id.duplicate_template:
                editTemplate(true);
                return true;

            case R.id.delete_account:
                deleteAccount();
                return true;
            case R.id.delete_transfer:
                deleteTransfer();
                return true;
            case R.id.delete_prognosis:
                deletePrognosis();
                return true;
            case R.id.delete_template:
                deleteTemplate();
                return true;

            case R.id.create:
                switch (viewMode) {
                    case VIEW_ACCOUNTS:
                        createAccount();
                        break;
                    case VIEW_TRANSFERS:
                        createTransfer();
                        break;
                    case VIEW_PROGNOSIS:
                        createPrognosis(null);
                        break;
                    case VIEW_TEMPLATES:
                        createTemplate();
                        break;
                }
                return true;

            case R.id.edit:
                switch (viewMode) {
                    case VIEW_ACCOUNTS:
                        editAccount(false);
                        break;
                    case VIEW_TRANSFERS:
                        editTransfer(false);
                        break;
                    case VIEW_PROGNOSIS:
                        editPrognosis(false);
                        break;
                    case VIEW_TEMPLATES:
                        editTemplate(false);
                        break;
                }
                return true;

            case R.id.duplicate:
                switch (viewMode) {
                    case VIEW_ACCOUNTS:
                        editAccount(true);
                        break;
                    case VIEW_TRANSFERS:
                        editTransfer(true);
                        break;
                    case VIEW_PROGNOSIS:
                        editPrognosis(true);
                        break;
                    case VIEW_TEMPLATES:
                        editTemplate(true);
                        break;
                }
                return true;

            case R.id.delete:
                switch (viewMode) {
                    case VIEW_ACCOUNTS:
                        deleteAccount();
                        break;
                    case VIEW_TRANSFERS:
                        deleteTransfer();
                        break;
                    case VIEW_PROGNOSIS:
                        deletePrognosis();
                        break;
                    case VIEW_TEMPLATES:
                        deleteTemplate();
                        break;
                }
                return true;

            case R.id.make_transfer:
                if (selectedPrognosis == null) {
                    toast(getResources().getString(R.string.msg_prognosis_not_selected));
                } else {
                    selectedPrognosis.mode = Balance.MODE_NORMAL;
                    selectedPrognosis.date = new Date();
                    selectedPrognosis.flags |= Balance.FLAG_INHERIT_TRANSFER;
                    intent = new Intent(this, EditBalance.class);
                    intent.putExtra("window_title", getResources().getString(R.string.transfer_title));
                    intent.putExtra("balance", selectedPrognosis);
                    startActivityForResult(intent, ACT_PROGNOSIS_TRANSFER);
                }
                return true;

            case R.id.deactivate_transfer:
                if (selectedTransfer.mode == Balance.MODE_NORMAL) {
                    selectedTransfer.flags &= 0x00FF;
                    selectedTransfer.flags |= Balance.FLAG_PERIOD_ONCE;
                    selectedTransfer.flags &= ~Balance.FLAG_INHERIT_TRANSFER;
                    selectedTransfer.parentID = -1;
                    selectedTransfer.mode = Balance.MODE_PROGNOSIS;
                    selectedTransfer.update();
                    viewTransfers.refresh(null);
                    refreshHeader();
                    toast(getResources().getString(R.string.msg_transfer_deactivated));
                }
                return true;

            case R.id.view_graph:
                if (viewMode == VIEW_PROGNOSIS) {
                    if (selectedPrognosis == null) {
                        toast(getResources().getString(R.string.msg_prognosis_not_selected));
                    } else {
                        intent = new Intent(this, ReportGraph.class);
                        intent.putExtra("prognosis", new Balance(db, selectedPrognosis.parentID));
                        startActivity(intent);
                    }
                } else {
                    if (selectedAccount == null) {
                        toast(getResources().getString(R.string.msg_account_notselected));
                    } else {
                        Balance c = db.getGraphRecord(selectedAccount);
                        if (c != null) {
                            intent = new Intent(this, ReportGraph.class);
                            intent.putExtra("prognosis", c);
                            startActivity(intent);
                        } else {
                            createPrognosis(selectedAccount);
                        }
                    }
                }
                return true;

            case R.id.view_analytics:
                if (viewMode == VIEW_ACCOUNTS) {
                    if (selectedAccount == null) {
                        toast(getResources().getString(R.string.msg_account_notselected));
                    } else {
                        intent = new Intent(this, ReportAnalytics.class);
                        intent.putExtra("account", selectedAccount);
                        startActivity(intent);
                    }
                }
                return true;


            case R.id.menu_accounts_prognose:
                if (selectedAccount == null) {
                    toast(getResources().getString(R.string.msg_account_notselected));
                } else {
                    createPrognosis(selectedAccount);
                }
                return true;

            /*
            case R.id.menu_accounts_correct:
                if (selectedAccount == null) {
                    toast(getResources().getString(R.string.msg_account_notselected));
                } else {
                    repairBalance(selectedAccount);
                }
                return true;
                */


            case R.id.set_auth:
                intent = new Intent(this, EditAuthentication.class);
                intent.putExtra("window_title", getResources().getString(R.string.prompt_chlogin));
                startActivityForResult(intent, ACT_SET_AUTH);
                return true;

            case R.id.menu_prognosis_list:
                setMode(VIEW_PROGNOSIS);
                return true;

            case R.id.menu_accounts_list:
                setMode(VIEW_ACCOUNTS);
                return true;

            case R.id.data_reset:
                db.garbageCollect();
                DropboxThread.dataReset();
                return true;

            //case R.id.data_collapse:
            //db.collapse(getFirst(Calendar.getInstance(TimeZone.getDefault())));
            //setMode(viewMode);
            //return true;
            case R.id.templates_export:
                viewTemplates.exportTemplates();
                return true;

            case R.id.templates_import:
                viewTemplates.importTemplates();
                viewTemplates.refresh();
                return true;

            case R.id.options:
                startActivity(new Intent(this, Settings.class));
                return true;

            case R.id.menu_about:
                new ViewAbout().show(getFragmentManager(), "fragment_view_about");
                return true;

            case R.id.sync:
                DropboxThread.dataChanged(); //.force();
                return true;

            case R.id.exit:
                finish();
                return true;

            default:
                return null;

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Boolean rc = doMenuAction(item.getItemId());
        if (rc != null) {
            return rc;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }


    void createAccount() {
        Intent inent = new Intent(this, EditAccount.class);
        inent.putExtra("window_title", getResources().getString(R.string.prompt_account));
        startActivityForResult(inent, ACT_NEW_ACCOUNT);
    }

    void createTemplate() {
        Balance balance = new Balance(db);
        balance.name = getResources().getString(R.string.sms_title);
        balance.mode = Balance.MODE_TEMPLATE;
        balance.flags |= Balance.FLAG_FORCE_TRANSFER;
        Intent inent = new Intent(this, EditBalance.class);
        inent.putExtra("window_title", getResources().getString(R.string.sms_title));
        inent.putExtra("balance", balance);
        startActivityForResult(inent, ACT_NEW_TEMPLATE);
    }

    void createPrognosis(Account ac) {
        Balance balance = new Balance(db);
        balance.name = getResources().getString(R.string.prognosis_title);
        balance.mode = Balance.MODE_PROGNOSIS;
        balance.flags &= ~0x00FF;
        balance.flags |= Balance.FLAG_PERIOD_ONCE;
        if (ac != null) {
            switch (ac.type) {
                case Account.TYPE_DEBT:
                case Account.TYPE_CARD:
                    balance.name = ac.name;
                    balance.accountTo = ac;
                    balance.flags &= ~0x00FF;
                    balance.flags |= Balance.FLAG_PERIOD_CREDIT;
                    balance.date = ac.date;
                    break;
                case Account.TYPE_NORMAL:
                    balance.accountFrom = ac;
                    break;
            }
        }
        Intent inent = new Intent(this, EditBalance.class);
        inent.putExtra("window_title", getResources().getString(R.string.prognosis_title));
        inent.putExtra("balance", balance);
        startActivityForResult(inent, ACT_NEW_PROGNOSIS);
    }

    void createTransfer() {
        Intent intent = new Intent(context, EditBalance.class);
        intent.putExtra("account", selectedAccount);
        startActivityForResult(intent, ACT_NEW_TRANSFER);
    }


    void editAccount(boolean copy) {
        if (selectedAccount == null) {
            toast(getResources().getString(R.string.msg_account_notselected));
        } else {
            Intent inent = new Intent(this, EditAccount.class);
            inent.putExtra("window_title", getResources().getString(R.string.prompt_account));
            inent.putExtra("account", selectedAccount);
            startActivityForResult(inent, copy ? ACT_NEW_ACCOUNT : ACT_EDIT_ACCOUNT);
        }
    }

    void editTemplate(boolean copy) {
        if (selectedTemplate == null) {
            toast(getResources().getString(R.string.msg_template_notselected));
        } else {
            Intent inent = new Intent(this, EditBalance.class);
            inent.putExtra("window_title", getResources().getString(R.string.sms_title));
            inent.putExtra("balance", selectedTemplate);
            startActivityForResult(inent, copy ? ACT_NEW_TEMPLATE : ACT_EDIT_TEMPLATE);
        }
    }

    void editPrognosis(boolean copy) {
        if (selectedPrognosis == null) {
            toast(getResources().getString(R.string.msg_prognosis_not_selected));
        } else {
            Intent inent = new Intent(this, EditBalance.class);
            inent.putExtra("window_title", getResources().getString(R.string.prognosis_title));
            inent.putExtra("balance", new Balance(db, selectedPrognosis.parentID));
            startActivityForResult(inent, copy ? ACT_NEW_PROGNOSIS : ACT_EDIT_PROGNOSIS);
        }
    }

    void editTransfer(boolean copy) {
        if (selectedTransfer == null) {
            toast(getResources().getString(R.string.msg_transfer_notselected));
        } else {
            Intent inent = new Intent(this, EditBalance.class);
            inent.putExtra("window_title", getResources().getString(R.string.transfer_title));
            inent.putExtra("balance", selectedTransfer);
            startActivityForResult(inent, copy ? ACT_NEW_TRANSFER : ACT_EDIT_TRANSFER);
        }
    }

    void deleteAccount() {
        if (selectedAccount == null) {
            toast(getResources().getString(R.string.msg_account_notselected));
        } else {
            selectedAccount.delete();
            selectedAccount = null;
            viewAccounts.refresh(null);
            refreshHeader();
            toast(getResources().getString(R.string.msg_account_deleted));
        }
    }

    void deleteTemplate() {
        if (selectedTemplate == null) {
            toast(getResources().getString(R.string.msg_template_notselected));
        } else {
            selectedTemplate.delete();
            selectedTemplate = null;
            viewTemplates.refresh();
            refreshHeader();
            toast(getResources().getString(R.string.msg_template_deleted));
        }
    }

    void deletePrognosis() {
        if (selectedPrognosis == null) {
            toast(getResources().getString(R.string.msg_prognosis_not_selected));
        } else {
            new Balance(db, selectedPrognosis.parentID).delete();
            selectedPrognosis = null;
            viewPrognosis.refresh();
            refreshHeader();
            toast(getResources().getString(R.string.msg_prognosis_deleted));
        }
    }

    void deleteTransfer() {
        if (selectedTransfer == null) {
            toast(getResources().getString(R.string.msg_transfer_notselected));
        } else {
            selectedTransfer.delete();
            selectedTransfer = null;
            viewAccounts.refresh(selectedAccount);
            viewTransfers.refresh();
            refreshHeader();
            toast(getResources().getString(R.string.msg_transfer_deleted));
        }
    }

    /*
    void repairBalance(Account ac) {
        Balance z = db.getLastSMSTransfer(ac);
        if (z != null) {
            Balance[] templates = db.getTemplates();
            boolean success = false;

            for (Balance t : templates) {
                MessageTemplate x = new MessageTemplate(t.template);
                if (x.parse(z.remark)) {
                    if (t.key.length() > 0 && !x.key.equals(t.key)) {
                        continue;
                    }

                    if (x.balance != 0) {

                        x.amount = ac.balance - x.balance;

                        Balance b = new Balance(db);
                        b.name = getResources().getString(R.string.balance_repair);
                        if (x.course != 0) {
                            x.amount = x.amount * x.course;
                        }

                        toast(getResources().getString(R.string.msg_sms_repaired));
                        return;
                    }

                }
            }
        }

        toast(getResources().getString(R.string.msg_no_sms_transfers));
    }
    */

    static void refreshCursor(ViewGroup view, int id, int bgColor) {
        for (int i = 0; i < view.getChildCount(); ++i) {
            if (i == id) {
                view.getChildAt(i).setBackgroundColor(Main.context.getResources().getColor(R.color.selected_color));
            } else {
                view.getChildAt(i).setBackgroundColor(bgColor);
            }
        }
    }

    /*
    @Override
    public void onBackPressed() {
        switch (viewMode) {
            case VIEW_ACCOUNTS:
                viewMode = VIEW_PROGNOSIS;
                break;

            case VIEW_TRANSFERS:
                viewMode = VIEW_ACCOUNTS;
                break;

            case VIEW_DETAILS:
                switch (selectedTransfer.mode) {
                    case Balance.MODE_NORMAL:
                        viewMode = VIEW_TRANSFERS;
                        break;
                    case Balance.MODE_TEMPLATE:
                        viewMode = VIEW_TEMPLATES;
                        break;

                    case Balance.MODE_PROGNOSIS:
                        viewMode = VIEW_PROGNOSIS;
                        break;
                }
                break;

            case VIEW_TEMPLATES:
                viewMode = VIEW_ACCOUNTS;
                break;

            case VIEW_PROGNOSIS:
                viewMode = VIEW_ACCOUNTS;
                break;

        }
        refreshView();

    }
    */

    /*
    void refreshView() {
        Point point = new Point();
        getWindowManager().getDefaultDisplay().getSize(point);

        screenWidth = point.x;
        screenHeight = point.y;

        //LinearLayout blockAccounts = (LinearLayout) findViewById(R.id.block_accounts);
        LinearLayout blockTransfers = (LinearLayout) findViewById(R.id.block_transfers);
        //LinearLayout blockDetails = (LinearLayout) findViewById(R.id.block_details);

        ImageView btnAction = (ImageView) findViewById(R.id.btnAction);
        btnAction.setFocusable(true);

        int accountsColor = getResources().getColor(R.color.background_color);
        int transfersColor = getResources().getColor(R.color.background_color);
        int detailsColor = getResources().getColor(R.color.background_color);

        if (screenWidth > screenHeight) {
            splitMode = SPLIT_DOUBLE;
            switch (viewMode) {
                case VIEW_ACCOUNTS:
                    widthAccounts = screenWidth * 40 / 100;
                    widthTransfers = screenWidth * 60 / 100;
                    widthDetails = 0;
                    accountsColor = getResources().getColor(R.color.background_color);
                    transfersColor = getResources().getColor(R.color.pane_color);
                    detailsColor = getResources().getColor(R.color.pane_color);

                    //blockAccounts.setBackgroundColor(getResources().getColor(R.color.background_color));
                    //blockTransfers.setBackgroundColor(getResources().getColor(R.color.pane_color));
                    break;

                case VIEW_PROGNOSIS:
                case VIEW_TEMPLATES:
                case VIEW_TRANSFERS:
                    widthAccounts = 0;
                    widthTransfers = screenWidth * 40 / 100;
                    widthDetails = screenWidth * 60 / 100;
                    accountsColor = getResources().getColor(R.color.background_color);
                    transfersColor = getResources().getColor(R.color.background_color);
                    detailsColor = getResources().getColor(R.color.pane_color);
                    //blockTransfers.setBackgroundColor(getResources().getColor(R.color.background_color));
                    //blockDetails.setBackgroundColor(getResources().getColor(R.color.pane_color));
                    break;
            }
        } else {
            splitMode = SPLIT_SINGLE;
            switch (viewMode) {
                case VIEW_ACCOUNTS:
                    widthAccounts = screenWidth;
                    widthTransfers = 0;
                    widthDetails = 0;
                    accountsColor = getResources().getColor(R.color.background_color);
                    transfersColor = getResources().getColor(R.color.background_color);
                    detailsColor = getResources().getColor(R.color.background_color);
                    //blockAccounts.setBackgroundColor(getResources().getColor(R.color.background_color));
                    break;

                case VIEW_PROGNOSIS:
                case VIEW_TEMPLATES:
                case VIEW_TRANSFERS:
                    widthAccounts = 0;
                    widthTransfers = screenWidth;
                    widthDetails = 0;
                    accountsColor = getResources().getColor(R.color.background_color);
                    transfersColor = getResources().getColor(R.color.background_color);
                    detailsColor = getResources().getColor(R.color.background_color);
                    //blockTransfers.setBackgroundColor(getResources().getColor(R.color.background_color));
                    break;

                case VIEW_DETAILS:
                    widthAccounts = 0;
                    widthTransfers = 0;
                    widthDetails = screenWidth;
                    accountsColor = getResources().getColor(R.color.background_color);
                    transfersColor = getResources().getColor(R.color.background_color);
                    detailsColor = getResources().getColor(R.color.background_color);
                    //blockDetails.setBackgroundColor(getResources().getColor(R.color.background_color));
                    break;
            }
        }


        //screenAccounts.setLayoutParams(new ViewGroup.LayoutParams(screenWidth, screenHeight));
        //screenPrognosis.setLayoutParams(new LayoutParams(screenWidth, screenHeight));


        if (widthAccounts != 0) {
            //blockAccounts.setVisibility(View.VISIBLE);
            //blockAccounts.setLayoutParams(new LinearLayout.LayoutParams(widthAccounts, LayoutParams.MATCH_PARENT));
            //blockAccounts.setBackgroundColor(accountsColor);
            //refreshAccounts(accountsColor);
        }

        if (widthTransfers != 0) {
            blockTransfers.setVisibility(View.VISIBLE);
            blockTransfers.setLayoutParams(new LayoutParams(widthTransfers, LayoutParams.MATCH_PARENT));
            blockTransfers.setBackgroundColor(transfersColor);

            switch (viewMode) {
                case VIEW_ACCOUNTS:
                case VIEW_TRANSFERS:
                    //refreshTransfers(transfersColor);
                    break;

            }
        }
        if (widthDetails != 0) {
            //blockDetails.setVisibility(View.VISIBLE);
            //blockDetails.setLayoutParams(new LayoutParams(widthDetails, LayoutParams.MATCH_PARENT));
            //blockDetails.setBackgroundColor(detailsColor);
            //refreshDetails(detailsColor);
        }

        if (widthAccounts == 0) {
            //blockAccounts.setVisibility(View.GONE);
        }
        if (widthTransfers == 0) {
            blockTransfers.setVisibility(View.GONE);
        }
        if (widthDetails == 0) {
            //blockDetails.setVisibility(View.GONE);
        }

        if (viewMode == VIEW_TEMPLATES) {
            btnAction.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Balance balance = new Balance();
                    balance.name = getResources().getString(R.string.sms_title);
                    balance.mode = Balance.MODE_TEMPLATE;
                    Intent inent = new Intent(context, EditBalance.class);
                    inent.putExtra("window_title", getResources().getString(R.string.sms_title));
                    inent.putExtra("balance", balance);
                    startActivityForResult(inent, ACT_NEW_TEMPLATE);
                }
            });

        } else if (viewMode == VIEW_PROGNOSIS) {
            btnAction.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Balance balance = new Balance();
                    balance.name = getResources().getString(R.string.prognosis_title);
                    balance.mode = Balance.MODE_PROGNOSIS;
                    balance.flags &= ~0x00FF;
                    balance.flags |= Balance.FLAG_PERIOD_ONCE;
                    Intent inent = new Intent(context, EditBalance.class);
                    inent.putExtra("window_title", getResources().getString(R.string.prognosis_title));
                    inent.putExtra("balance", balance);
                    startActivityForResult(inent, ACT_NEW_PROGNOSIS);
                }
            });

        } else {
            if (splitMode == SPLIT_SINGLE && viewMode == VIEW_DETAILS) {
                btnAction.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(context, EditBalance.class);
                        intent.putExtra("balance", selectedTransfer);
                        startActivityForResult(intent, ACT_EDIT_TRANSFER);
                    }
                });
            } else {
                btnAction.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(context, EditBalance.class);
                        intent.putExtra("account", selectedAccount);
                        startActivityForResult(intent, ACT_NEW_TRANSFER);
                    }
                });
            }

            btnAction.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    Intent intent = new Intent(context, EditBalance.class);
                    startActivityForResult(intent, ACT_NEW_TRANSFER);
                    return true;
                }
            });
        }
    }
    */

    /*
    void refreshAccounts(int color) {

        final int bgColor = color;

        //final int bgColor = getResources().getColor(R.color.background_color);

        accounts = db.getAccountsList();
        TableLayout container = (TableLayout) findViewById(R.id.container_accounts);
        container.setColumnShrinkable(1, true);
        container.setColumnStretchable(1, true);
        container.removeAllViews();
        //container.setBackgroundColor(bgColor);

        double amount = 0.0;
        double debt = 0.0;
        double normal = 0.0;

        int id = -1;
        View current = null;

        if (selectedAccount == null && accounts.length > 0) {
            selectedAccount = accounts[0];
        }

        for (int i = 0; i < accounts.length; ++i) {

            String nm = accounts[i].name;
            if (accounts[i].type == Account.TYPE_CARD) {
                amount += accounts[i].balance;
            } else {
                amount += accounts[i].balanceDebt;
            }
            debt += accounts[i].balanceCredit;
            normal += accounts[i].balanceDebt;

            String subTitle = datetimeString(accounts[i].last);
            ImageView icon = new ImageView(context);
            switch (accounts[i].type) {
                case Account.TYPE_NORMAL:
                    icon.setImageDrawable(getResources().getDrawable(R.drawable.wallet));
                    break;
                case Account.TYPE_DEBT:
                    icon.setImageDrawable(getResources().getDrawable(R.drawable.credit));
                    break;
                case Account.TYPE_CARD:
                    icon.setImageDrawable(getResources().getDrawable(R.drawable.card));
                    subTitle += " " + getResources().getString(R.string.account_amount_limit_short)
                            + String.format(" %.2f", accounts[i].amount);
                    break;
            }

            icon.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            icon.setAdjustViewBounds(true);
            icon.setMaxHeight(32);
            icon.setMaxWidth(32);
            icon.setPadding(0, 4, 0, 0);

            LinearLayout iconHolder = new LinearLayout(context);
            iconHolder.addView(icon);
            LayoutParams param = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            iconHolder.setLayoutParams(param);


            TableLayout title = new TableLayout(context);
            title.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            title.setColumnShrinkable(1, true);
            title.setColumnStretchable(1, true);

            TextView x = getTextView(this, accounts[i].name);
            x.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            x.setTextSize(16);

            TableRow row = new TableRow(this);
            row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            row.addView(x);
            title.addView(row);

            x = getTextView(this, subTitle);
            x.setTextSize(12);

            row = new TableRow(this);
            row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            row.addView(x);
            title.addView(row);

            //TextView type = getTextView(adapter.getItem(accounts[i].type));
            //type.setWidth(50);

            TextView balance = getTextView(this, String.format("%.2f", accounts[i].balance));
            balance.setGravity(Gravity.RIGHT);
            balance.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            balance.setTextSize(16);
            balance.setTextColor(getAccountColor(accounts[i]));

            TableRow xrow = addRow(this, bgColor, i, new View[]{
                    iconHolder,
                    title,
                    balance
            });

            xrow.setTag(tagAccount);

            xrow.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    int id = view.getId();
                    selectedAccount = accounts[id];
                    refreshCursor((ViewGroup) view.getParent(), id, bgColor);
                    return false;  //To change body of implemented methods use File | Settings | File Templates.
                }
            });

            xrow.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    ViewGroup v = (ViewGroup) view.getParent();
                    int id = view.getId();

                    selectedAccount = accounts[id];
                    if (splitMode == SPLIT_DOUBLE) {
                        refreshTransfers(getResources().getColor(R.color.pane_color));
                        //refreshCursor(v, id, bgColor);
                    } else {
                        viewMode = VIEW_TRANSFERS;
                        refreshView();
                    }

                    //refreshCursor(v, id, bgColor);
                }
            });


            registerForContextMenu(xrow);
            container.addView(xrow); //индекс можно убрать.

            if (selectedAccount != null && accounts[i].accountID == selectedAccount.accountID) {
                id = i;
                current = xrow;
            }
        }


        if (id != -1) {
            refreshCursor(container, id, bgColor);
            ((ScrollView) findViewById(R.id.scroll_accounts)).scrollTo(0, current.getTop());
        }

        if (viewMode == VIEW_ACCOUNTS) {


            TextView accountTitle = (TextView) findViewById(R.id.account_title);
            //TextView accountAmount = (TextView) findViewById(R.id.account_amount);
            //TextView accountDebt = (TextView) findViewById(R.id.account_debt);
            TextView amountBalance = (TextView) findViewById(R.id.amount_balance);
            TextView amountDebt = (TextView) findViewById(R.id.amount_debt);
            TextView amountNormal = (TextView) findViewById(R.id.amount_normal);
            LinearLayout blockLines = (LinearLayout) findViewById(R.id.block_lines);
            LinearLayout blockColumns = (LinearLayout) findViewById(R.id.block_columns);

            blockLines.setVisibility(View.GONE);
            blockColumns.setVisibility(View.VISIBLE);

            ImageView icon = (ImageView) findViewById(R.id.icon);
            icon.setImageDrawable(null);

            blockLines.setVisibility(View.GONE);
            blockColumns.setVisibility(View.VISIBLE);

            accountTitle.setText(getResources().getText(R.string.prompt_accounts));
            amountBalance.setText(String.format("%.2f", amount));
            amountDebt.setText(String.format("%.2f", debt));
            amountNormal.setText(String.format("%.2f", normal));

            //accountAmount.setText(getResources().getString(R.string.prompt_account_amount, amount));
            //accountDebt.setText(getResources().getString(R.string.prompt_account_debt, debt));
        }
    }
    */


    /*
    void refreshTransfers(int color) {

        final int bgColor = color;

        TableLayout container = (TableLayout) findViewById(R.id.container_transfers);
        container.setColumnShrinkable(1, true);
        container.setColumnStretchable(1, true);
        container.removeAllViews();
        //container.setBackgroundColor(bgColor);


        TextView accountTitle = (TextView) findViewById(R.id.account_title);
        TextView accountBalance = (TextView) findViewById(R.id.account_amount);
        TextView accountDetails = (TextView) findViewById(R.id.account_debt);
        ImageView accountIcon = (ImageView) findViewById(R.id.icon);

        LinearLayout blockLines = (LinearLayout) findViewById(R.id.block_lines);
        LinearLayout blockColumns = (LinearLayout) findViewById(R.id.block_columns);


        if (viewMode == VIEW_ACCOUNTS || viewMode == VIEW_TRANSFERS) {
            if (selectedAccount == null) return;
            selectedAccount.refreshBalance();
        }


        switch (viewMode) {
            case VIEW_TEMPLATES:
                transfers = db.getTemplates();
                break;

            case VIEW_ACCOUNTS:
            case VIEW_DETAILS:
            case VIEW_TRANSFERS:
                transfers = db.getTransfers(selectedAccount);
                break;

            case VIEW_PROGNOSIS:
                transfers = db.getPrognosis(viewPeriod);
                break;
        }

        if (selectedTransfer == null && transfers.length > 0) {
            selectedTransfer = transfers[0];
        }

        double balance = 0.0;
        double balanceDebt = 0.0;
        double balanceCredit = 0.0;


        int id = -1;
        View current = null;

        if (selectedTransfer == null && transfers.length > 0) {
            selectedTransfer = transfers[transfers.length - 1];
        }


        if (viewMode != VIEW_PROGNOSIS) {
            balance = selectedAccount == null ? 0.0 : selectedAccount.amount;
        }

        TableRow xrow = null;

        for (int i = 0; i < transfers.length; ++i) {
            Balance transfer = transfers[i];
            //boolean approved = new Balance(selectedTransfer.parentID).approved(viewPeriod);

            double transferAmount = 0.0;
            String subTitle = "";

            ImageView icon = new ImageView(context);
            icon.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            icon.setAdjustViewBounds(true);
            icon.setMaxHeight(32);
            icon.setMaxWidth(32);
            icon.setPadding(0, 4, 0, 0);

            LinearLayout iconHolder = new LinearLayout(context);
            iconHolder.addView(icon);
            LayoutParams param = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            iconHolder.setLayoutParams(param);

            if (viewMode == VIEW_TEMPLATES) {
                transferAmount = transfer.amount;
                icon.setImageDrawable(getResources().getDrawable(R.drawable.bubble));
                subTitle = "";
                if (transfer.accountFrom != null) {
                    subTitle += transfer.accountFrom.name;
                }
                if (transfer.accountTo != null) {
                    if (subTitle.length() > 0) {
                        subTitle += " -> ";
                    }
                    subTitle += transfer.accountTo.name;
                }
            } else if (viewMode == VIEW_PROGNOSIS) {
                transferAmount = transfer.amount;
                balance += transfer.amount;
                if (transfer.approved) {
                    balanceDebt += transfer.amount;
                } else {
                    balanceCredit += transfer.amount;
                }

                if (transfer.approved) {
                    icon.setImageDrawable(getResources().getDrawable(R.drawable.tick));
                } else if (transfer.date.before(new Date())) {
                    icon.setImageDrawable(getResources().getDrawable(R.drawable.warning));
                } else if ((transfer.flags & 0xFF) == Balance.FLAG_PERIOD_CREDIT
                        && transfer.accountTo != null && transfer.accountTo.type == Account.TYPE_DEBT) {
                    icon.setImageDrawable(getResources().getDrawable(R.drawable.credit));
                } else if ((transfer.flags & 0xFF) == Balance.FLAG_PERIOD_CREDIT
                        && transfer.accountTo != null && transfer.accountTo.type == Account.TYPE_CARD) {
                    icon.setImageDrawable(getResources().getDrawable(R.drawable.card));
                } else {
                    icon.setImageDrawable(getResources().getDrawable(R.drawable.calendar));
                }
                subTitle = "";
                if (transfer.accountFrom != null) {
                    subTitle += transfer.accountFrom.name;
                }
                if (subTitle.length() > 0) {
                    subTitle += " -> ";
                } else {
                    subTitle += getResources().getString(R.string.transfer_empty);
                }

                if (transfer.type == Balance.TYPE_COMPLEX) {
                    String s = "";
                    for (Complex c : transfer.complex) {
                        if (s.length() > 0) s += ", ";
                        if (c.account != null) {
                            s += c.account.name;
                        } else {
                            s += getResources().getString(R.string.transfer_empty);
                        }
                    }
                    subTitle += s;
                } else if (transfer.accountTo != null) {
                    subTitle += transfer.accountTo.name;
                } else {
                    subTitle += getResources().getString(R.string.transfer_empty);
                }

            } else {
                if (transfer.accountFrom != null
                        && selectedAccount != null
                        && transfer.accountFrom.accountID == selectedAccount.accountID) {
                    transferAmount = transfer.amount;
                    icon.setImageDrawable(getResources().getDrawable(R.drawable.out));
                    balance -= transferAmount * (selectedAccount.type == Account.TYPE_DEBT ? -1 : 1);

                    if (transfer.type == Balance.TYPE_COMPLEX) {
                        subTitle = "";
                        for (Complex c : transfer.complex) {
                            if (subTitle.length() > 0) subTitle += ", ";
                            if (c.account != null) {
                                subTitle += c.account.name;
                            } else {
                                subTitle += getResources().getString(R.string.transfer_empty);
                            }
                        }
                    } else if (transfer.accountTo != null) {
                        subTitle = transfer.accountTo.name;
                    } else {
                        subTitle = getResources().getString(R.string.transfer_empty);
                    }
                } else {
                    if (transfer.type == Balance.TYPE_NORMAL) {
                        transferAmount = transfer.amount;
                    } else {
                        transferAmount = 0;
                        for (Complex c : transfer.complex) {
                            if (c.account != null && c.account.accountID == selectedAccount.accountID) {
                                transferAmount += c.amount;
                            }
                        }
                    }
                    if (transfer.accountFrom != null) {
                        subTitle = transfer.accountFrom.name;
                    } else {
                        subTitle = getResources().getString(R.string.transfer_empty);
                    }
                    icon.setImageDrawable(getResources().getDrawable(R.drawable.in));
                    balance += transferAmount * (selectedAccount.type == Account.TYPE_DEBT ? -1 : 1);
                }
            }


            LinearLayout column2 = new LinearLayout(context);
            column2.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            column2.setOrientation(LinearLayout.VERTICAL);

            TextView name = Main.getTextView(this, transfer.name);
            name.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            name.setTextSize(16);
            correctColor(transfer, name);


            LinearLayout subrow = new LinearLayout(context);
            subrow.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            subrow.setOrientation(LinearLayout.HORIZONTAL);

            TextView date = Main.getTextView(this, Main.datetimeString(transfer.date));
            date.setTextSize(12);
            date.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            date.setTextColor(getResources().getColor(R.color.total_color));
            correctColor(transfer, date);

            TextView sub = Main.getTextView(this, subTitle);
            sub.setTextSize(12);
            sub.setPadding(8, 0, 0, 0);
            correctColor(transfer, sub);


            subrow.addView(date);
            subrow.addView(sub);

            column2.addView(name);
            column2.addView(subrow);

            String anal = "";
            for (Analytics a : transfer.analytics.keySet()) {
                if (transfer.analytics.get(a) != null) {
                    if (anal.length() > 0) anal += ", ";
                    anal += transfer.analytics.get(a).name;
                }
            }

            if (anal.length() > 0) {
                TextView vanal = Main.getTextView(this, anal);
                vanal.setTextSize(12);
                vanal.setTextColor(getResources().getColor(R.color.list_color));
                correctColor(transfer, vanal);
                column2.addView(vanal);
            }

            LinearLayout column3 = new LinearLayout(context);
            column3.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            column3.setOrientation(LinearLayout.VERTICAL);

            if (viewMode != VIEW_TEMPLATES) {
                TextView amount = Main.getTextView(this, String.format("%.2f", transferAmount));
                amount.setGravity(Gravity.RIGHT);
                amount.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
                amount.setTextSize(16);
                correctColor(transfer, amount);
                column3.addView(amount);

                if (viewMode != VIEW_PROGNOSIS) {
                    TextView bal = Main.getTextView(this, String.format("%.2f", balance));
                    bal.setTextSize(12);
                    bal.setGravity(Gravity.RIGHT);
                    column3.addView(bal);
                }
            }

            xrow = Main.addRow(this, bgColor, i, new View[]{
                    iconHolder,
                    column2,
                    column3
            });

            xrow.setTag(tagTransfer);

            //if (viewMode == VIEW_PROGNOSIS) {
            ///recolor(xrow, getResources().getColor(R.color.approved));
            //}

            xrow.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    int id = view.getId();
                    selectedTransfer = transfers[id];
                    refreshCursor((ViewGroup) view.getParent(), id, bgColor);
                    return false;  //To change body of implemented methods use File | Settings | File Templates.
                }
            });

            xrow.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {

                    ViewGroup v = (ViewGroup) view.getParent();
                    int id = view.getId();

                    selectedTransfer = transfers[view.getId()];
                    if (splitMode == SPLIT_DOUBLE && (viewMode == VIEW_TRANSFERS || viewMode == VIEW_TEMPLATES)) {
                        refreshDetails(getResources().getColor(R.color.pane_color));
                        //refreshCursor(v, id, bgColor);
                    } else if (splitMode == SPLIT_DOUBLE && viewMode == VIEW_ACCOUNTS) {
                        viewMode = VIEW_TRANSFERS;
                        refreshView();
                    } else if (splitMode == SPLIT_SINGLE) {
                        viewMode = VIEW_DETAILS;
                        refreshView();
                    }

                    //refreshCursor(v, id, bgColor);

                }
            });

            registerForContextMenu(xrow);
            container.addView(xrow);

            if (selectedTransfer != null && transfers[i].balanceID == selectedTransfer.balanceID) {
                id = i;
                current = xrow;
            }

        }


        if (id != -1) {
            refreshCursor(container, id, bgColor);
            ((ScrollView) findViewById(R.id.scroll_transfers)).post(
                    new ScrollTo(((ScrollView) findViewById(R.id.scroll_transfers)), current));
        } else if (xrow != null && viewMode != VIEW_PROGNOSIS && viewMode != VIEW_TEMPLATES) {
            ((ScrollView) findViewById(R.id.scroll_transfers)).post(
                    new ScrollTo(((ScrollView) findViewById(R.id.scroll_transfers)), xrow));
        }

        if (viewMode == VIEW_TRANSFERS) {
            blockLines.setVisibility(View.VISIBLE);
            blockColumns.setVisibility(View.GONE);

            accountTitle.setText(selectedAccount.name);
            accountBalance.setText(getResources().getString(R.string.account_balance, selectedAccount.balance));
            if (selectedAccount.balanceCredit > 0 && selectedAccount.balanceCredit != selectedAccount.balance) {
                accountDetails.setText(getResources().getString(R.string.account_credit, selectedAccount.balanceCredit));
            } else if (selectedAccount.balanceDebt > 0 && selectedAccount.balanceDebt != selectedAccount.balance) {
                accountDetails.setText(getResources().getString(R.string.account_debt, selectedAccount.balanceDebt));
            }

            switch (selectedAccount.type) {
                case Account.TYPE_NORMAL:
                    accountIcon.setImageDrawable(getResources().getDrawable(R.drawable.wallet));
                    break;
                case Account.TYPE_DEBT:
                    accountIcon.setImageDrawable(getResources().getDrawable(R.drawable.credit));
                    break;
                case Account.TYPE_CARD:
                    accountIcon.setImageDrawable(getResources().getDrawable(R.drawable.card));
                    break;
            }

        } else if (viewMode == VIEW_TEMPLATES) {
            accountTitle.setText(getResources().getString(R.string.menu_templates));
            accountIcon.setImageDrawable(getResources().getDrawable(R.drawable.bubble));
            accountBalance.setText("\n");
            accountDetails.setText("\n");
        } else if (viewMode == VIEW_PROGNOSIS) {
            accountIcon.setImageDrawable(getResources().getDrawable(R.drawable.calendar));
            accountTitle.setText(
                    String.format("%tb %tY: %s",
                            viewPeriod[0],
                            viewPeriod[0],
                            getResources().getString(R.string.menu_prognosis)));
            accountBalance.setText(getResources().getString(R.string.prompt_payment_total, balance));
            accountDetails.setText(getResources().getString(R.string.prompt_payment_payed, balanceDebt));
        }
    }
    */


    /*
    void refreshTransfers(int bgColor) {

        LinearLayout blockDetails = (LinearLayout) findViewById(R.id.block_transfers);
        blockDetails.removeAllViews();
        switch(viewMode) {

            case VIEW_ACCOUNTS:
            case VIEW_TRANSFERS:
                blockDetails.addView(new ViewDetails(selectedTransfer, bgColor, context));
                break;

            case VIEW_TEMPLATES:
                blockDetails.addView(new ViewTemplates(context));
                break;

            case VIEW_PROGNOSIS:
                blockDetails.addView(new ViewPrognosis(viewPeriod, context));
                break;

        }
    }
    */

    /*
    void refreshDetails(int bgColor) {

        LinearLayout blockDetails = (LinearLayout) findViewById(R.id.block_details);
        blockDetails.removeAllViews();
        blockDetails.addView(new ViewDetails(selectedTransfer, bgColor, context));
        */

    /*
    int bgColor = (splitMode == SPLIT_SINGLE) ?
            getResources().getColor(R.color.background_color) :
            getResources().getColor(R.color.pane_color);

    LinearLayout container = (LinearLayout) findViewById(R.id.container_details);
    //container.setBackgroundColor(bgColor);

    //TableLayout container = (TableLayout) findViewById(R.id.container_transfer);
    if (selectedTransfer == null) return;

    TableLayout complexContainer = (TableLayout) findViewById(R.id.container_complex);
    TableLayout analyticsContainer = (TableLayout) findViewById(R.id.container_analytics);
    LinearLayout blockTo = (LinearLayout) findViewById(R.id.block_to);
    LinearLayout blockComplex = (LinearLayout) findViewById(R.id.block_complex);

    TextView datePlace = (TextView) findViewById(R.id.date_place);
    TextView balanceFrom = (TextView) findViewById(R.id.balance_from);
    TextView balanceTo = (TextView) findViewById(R.id.balance_to);
    TextView transferFrom = (TextView) findViewById(R.id.transfer_from);
    TextView transferTo = (TextView) findViewById(R.id.transfer_to);

    TextView remarkTitle = (TextView) findViewById(R.id.remark_title);
    TextView analyticsTitle = (TextView) findViewById(R.id.analytics_title);


    TextView name = (TextView) findViewById(R.id.transfer_name);
    TextView from = (TextView) findViewById(R.id.from);
    TextView to = (TextView) findViewById(R.id.to);
    TextView amount = (TextView) findViewById(R.id.amount);
    TextView remark = (TextView) findViewById(R.id.remark);

    selectedTransfer.refresh();

    if (splitMode == SPLIT_SINGLE) {
        TextView accountTitle = (TextView) findViewById(R.id.account_title);
        TextView accountBalance = (TextView) findViewById(R.id.account_amount);
        TextView accountDetails = (TextView) findViewById(R.id.account_debt);
        ImageView icon = (ImageView) findViewById(R.id.icon);

        accountTitle.setText(selectedTransfer.name);
        accountBalance.setText(getResources().getString(R.string.transfer_amount_value, selectedTransfer.amount));
        accountDetails.setText("");
        icon.setImageDrawable(null);
    }

    //container.setColumnShrinkable(1, true);
    //container.setColumnStretchable(1, true);

    //listContainer.removeAllViews();
    //container.removeAllViews();

    name.setText(selectedTransfer.name);
    if (selectedTransfer.accountFrom == null) {
        from.setText(getResources().getString(R.string.transfer_empty));
    } else {
        from.setText(selectedTransfer.accountFrom.name);
    }

    balanceFrom.setText("");

    if (selectedTransfer.accountTo == null) {
        to.setText(getResources().getString(R.string.transfer_empty));
    } else {
        to.setText(selectedTransfer.accountTo.name);
    }

    balanceTo.setText("");

    remark.setText(selectedTransfer.remark);
    datePlace.setText(datetimeFullString(selectedTransfer.date));

    complexContainer.removeAllViews();

    if (selectedTransfer.type != Balance.TYPE_COMPLEX) {
        blockComplex.setVisibility(View.GONE);
        blockTo.setVisibility(View.VISIBLE);

        amount.setText("" + selectedTransfer.amount);
    } else {
        blockComplex.setVisibility(View.VISIBLE);
        blockTo.setVisibility(View.GONE);

        amount.setText("0.00");

        int i = 0;
        for (Complex c : selectedTransfer.complex) {

            TextView ttl = Main.getTextView(context, c.name);
            ttl.setTextSize(12);
            ttl.setTypeface(Typeface.DEFAULT, Typeface.BOLD);

            TextView acc = Main.getTextView(context,
                    c.account == null
                            ? getResources().getString(R.string.transfer_empty)
                            : c.account.name);
            acc.setTextColor(Main.getAccountColor(c.account));
            acc.setTextSize(12);

            LinearLayout col = new LinearLayout(context);
            col.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            col.setOrientation(LinearLayout.VERTICAL);
            col.addView(ttl);
            col.addView(acc);


            TextView amt = Main.getTextView(context, String.format("%.2f", c.amount));
            amt.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            amt.setTextSize(18);
            amt.setGravity(Gravity.RIGHT);

            TableRow row = Main.addRow(context, bgColor, i++, new View[]{col, amt});
            complexContainer.addView(row);
        }

        TextView amt = Main.getTextView(context, String.format("%.2f", selectedTransfer.amount));
        amt.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
        amt.setTextSize(18);
        amt.setTextColor(getResources().getColor(R.color.total_color));
        amt.setGravity(Gravity.RIGHT);
        amt.setPadding(0, 0, 0, 16);

        complexContainer.addView(Main.addRow(context, bgColor, -1, new View[]{
                Main.getTextView(context, ""),
                amt
        }));
    }


    analyticsContainer.removeAllViews();

    for (final Analytics section : selectedTransfer.analytics.keySet()) {

        Analytics current = selectedTransfer.analytics.get(section);
        if (current != null) {

            TextView title = getTextView(context, section.name);
            title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            title.setSingleLine(true);
            title.setEllipsize(TruncateAt.END);
            title.setPadding(0, 0, 8, 0);

            TextView value = getTextView(context, current.name);
            value.setSingleLine(true);
            value.setEllipsize(TruncateAt.END);

            TableRow row = new TableRow(context);
            row.addView(title);
            row.addView(value);

            analyticsContainer.addView(row);
        }
    }

    if (selectedTransfer.remark.length() == 0) {
        remarkTitle.setVisibility(View.GONE);
    } else {
        remarkTitle.setVisibility(View.VISIBLE);
    }

    if (selectedTransfer.analytics.size() == 0) {
        analyticsTitle.setVisibility(View.GONE);
    } else {
        analyticsTitle.setVisibility(View.VISIBLE);
    }
    */

    //}


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

        MenuInflater inflater = new MenuInflater(this);
        super.onCreateContextMenu(menu, v, menuInfo);

        if (v.getTag().equals(tagAccount)) {

            //selectedAccount = accounts[v.getId()];
            menu.setHeaderTitle(/*getResources().getString(R.string.accounts) + " : " +*/ selectedAccount.name);
            inflater.inflate(R.menu.accounts, menu);

        } else if (v.getTag().equals(tagTransfer)) {

            //selectedTransfer = transfers[v.getId()];
            menu.setHeaderTitle(/*getResources().getString(R.string.transfer_title)*/selectedTransfer.name + " : " + selectedTransfer.amount);
            inflater.inflate(R.menu.transfers, menu);

        } else if (v.getTag().equals(tagTemplate)) {

            //selectedTransfer = transfers[v.getId()];
            menu.setHeaderTitle(/*getResources().getString(R.string.menu_templates) + " : " + */ selectedTemplate.name);
            inflater.inflate(R.menu.templates, menu);

        } else if (v.getTag().equals(tagPrognosis)) {

            //selectedTransfer = transfers[v.getId()];
            menu.setHeaderTitle(/*getResources().getString(R.string.menu_prognosis)+ " : " + */selectedPrognosis.name);
            inflater.inflate(R.menu.prognosis, menu);

        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        Boolean rc = doMenuAction(item.getItemId());
        if (rc != null) {
            return rc;
        } else {
            return super.onContextItemSelected(item);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //if (!loggedIn) {
        //    finish();
        //} else {
        DropboxThread.checkLogin();
        //}

    }


    //////////////////////////////////////////


    public static String dateString(Date d) {
        Calendar c = Calendar.getInstance(TimeZone.getDefault());
        c.setTime(d);
        return String.format("%02d.%02d.%02d",
                c.get(Calendar.DAY_OF_MONTH),
                c.get(Calendar.MONTH) + 1,
                c.get(Calendar.YEAR));
    }

    public static String datetimeString(Date d) {
        Calendar c = Calendar.getInstance(TimeZone.getDefault());
        c.setTime(d);
        return String.format("%02d.%02d %02d:%02d",
                c.get(Calendar.DAY_OF_MONTH),
                c.get(Calendar.MONTH) + 1,
                c.get(Calendar.HOUR_OF_DAY),
                c.get(Calendar.MINUTE));
    }

    public static String datetimeFullString(Date d) {
        Calendar c = Calendar.getInstance(TimeZone.getDefault());
        c.setTime(d);
        return String.format("%02d.%02d.%04d %02d:%02d",
                c.get(Calendar.DAY_OF_MONTH),
                c.get(Calendar.MONTH) + 1,
                c.get(Calendar.YEAR),
                c.get(Calendar.HOUR_OF_DAY),
                c.get(Calendar.MINUTE));
    }

    public static String dateFullString(Date d) {
        Calendar c = Calendar.getInstance(TimeZone.getDefault());
        c.setTime(d);
        return String.format("%02d.%02d.%04d",
                c.get(Calendar.DAY_OF_MONTH),
                c.get(Calendar.MONTH) + 1,
                c.get(Calendar.YEAR));
    }

    public static CharSequence cutString(CharSequence str, int limit) {
        String trail = "..";
        if (str.length() > limit - trail.length()) {
            return str.toString().substring(0, limit - trail.length()) + trail;
        } else {
            return str;
        }
    }


    public static Account getAccount(long id) {
        if (id < 0) {
            return null;
        }
        for (Account ac : accounts) {
            if (ac.accountID == id) {
                return ac;
            }
        }
        return null;
    }

    public static Account getAccountByIndex(int id) {
        if (id < 0) {
            return null;
        }
        return accounts[id];
    }

    public Account getAccountByName(String name) {
        for (Account ac : accounts) {
            if (ac.name.equals(name)) {
                return ac;
            }
        }
        return null;
    }

    public static int getAccountIndex(Account ac) {
        if (ac == null) {
            return -1;
        }
        for (int i = 0; i < accounts.length; ++i) {
            if (ac.accountID == accounts[i].accountID) {
                return i;
            }
        }
        return -1;
    }


    public static int getAccountColor(Account ac) {
        if (ac == null) {
            return context.getResources().getColor(R.color.text_color);
        }
        switch (ac.type) {
            case Account.TYPE_NORMAL:
                return context.getResources().getColor(R.color.ac_normal_color);
            case Account.TYPE_DEBT:
                if (ac.balance > 0) {
                    return context.getResources().getColor(R.color.ac_debt_color);
                } else {
                    return context.getResources().getColor(R.color.ac_normal_color);
                }
            case Account.TYPE_CARD:
                if (ac.balance < ac.amount) {
                    return context.getResources().getColor(R.color.ac_card_color);
                } else {
                    return context.getResources().getColor(R.color.ac_normal_color);
                }
        }
        return context.getResources().getColor(R.color.text_color);
    }

    public static TableRow addRow(Context context, int bgColor, int id, View[] columns) {
        TableRow row = new TableRow(context);

        TableLayout.LayoutParams param = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        param.setMargins(0, 0, 0, 1);
        row.setLayoutParams(param);

        row.setBackgroundColor(bgColor);
        row.setId(id);
        row.setClickable(true);
        row.setFocusable(true);
        row.setPadding(0, 4, 0, 4);

        if (columns != null) {
            for (View v : columns) {
                v.setPadding(7, 0, 7, 0);
                v.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
                //v.setBackgroundColor(bgColor);
                row.addView(v);

            }
        }
        return row;
    }

    public static TextView getTextView(Context context, CharSequence val) {
        TextView name = new TextView(context);
        name.setText(val);
        name.setSingleLine(true);
        name.setEllipsize(TruncateAt.END);
        name.setTextColor(context.getResources().getColor(R.color.text_color));
        return name;

    }

    public static void toast(String text) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    public static void toast(int id) {
        Toast.makeText(context, context.getResources().getString(id), Toast.LENGTH_SHORT).show();
    }


    public static double eval(String expression, Double balance) {
        double result = 0.00;
        try {
            String a = expression;
            a = a.replace("=", "");
            if (balance != null) {
                a = a.replace("$", String.format("%.2f", balance));
            }
            result = new Eval(a).evaluate();
        } catch (Exception e) {
        }
        return result;
    }

    public static Calendar[] getPeriod(int period, Date d) {
        Calendar c = Calendar.getInstance(TimeZone.getDefault());
        c.setTime(d);
        return getPeriod(period, c);
    }

    public static Calendar[] getViewPeriod(Date d) {
        Calendar[] z = getPeriod(Calendar.MONTH, d);
        z[1].add(Calendar.DAY_OF_MONTH, context.getSharedPreferences(Main.PREFERENCES_NAME, 0).getInt("PROGNOSIS_DAYS_AFTER", 10));
        return z;
    }

    public static Calendar getFirst(Calendar at) {
        Calendar c = (Calendar) at.clone();
        c.set(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c;
    }

    public static Calendar[] getPeriod(int period, Calendar d) {
        Calendar[] result = new Calendar[2];
        result[0] = (Calendar) d.clone(); //Calendar.getInstance(TimeZone.getDefault());
        result[1] = (Calendar) d.clone(); //Calendar.getInstance(TimeZone.getDefault());

        result[0].set(Calendar.HOUR, 0);
        result[0].set(Calendar.MINUTE, 0);
        result[0].set(Calendar.SECOND, 0);
        result[0].set(Calendar.MILLISECOND, 0);
        result[1].set(Calendar.HOUR, 23);
        result[1].set(Calendar.MINUTE, 59);
        result[1].set(Calendar.SECOND, 59);
        result[1].set(Calendar.MILLISECOND, 999);

        switch (period) {
            case Calendar.DAY_OF_MONTH:
                break;

            case Calendar.WEEK_OF_MONTH:
                while (result[0].get(Calendar.DAY_OF_WEEK) != Calendar.getInstance(TimeZone.getDefault()).getFirstDayOfWeek()) {
                    result[0].add(Calendar.DAY_OF_WEEK, -1);
                    result[1].add(Calendar.DAY_OF_WEEK, -1);
                }
                result[1].add(Calendar.DAY_OF_MONTH, 5);
                break;

            case Calendar.MONTH:
                result[0].set(Calendar.DAY_OF_MONTH, 1);
                result[1].set(Calendar.DAY_OF_MONTH, 1);
                result[1].add(Calendar.MONTH, 1);
                result[1].add(Calendar.DAY_OF_MONTH, -2);
                break;

            case Calendar.YEAR:
                result[0].set(Calendar.DAY_OF_MONTH, 1);
                result[0].set(Calendar.MONTH, Calendar.JANUARY);
                result[1].set(Calendar.DAY_OF_MONTH, 31);
                result[1].set(Calendar.MONTH, Calendar.DECEMBER);
        }
        return result;
    }


    public static void showNotification(Context context, String text) {

        Intent intent = null;
        if (Main.context == null) {
            intent = new Intent(context, Main.class);
            intent.setAction("android.intent.action.MAIN");
            intent.addCategory("android.intent.category.LAUNCHER");
        } else {
            intent = new Intent(Main.context, Main.class);
        }

        //ЗАПУСКАЕТСЯ ВТОРОЙ

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        Notification.Builder builder = new Notification.Builder(context)
                .setContentTitle(context.getResources().getString(R.string.app_name))
                .setContentText(text)
                .setContentIntent(contentIntent)
                .setSmallIcon(R.drawable.icon)
                .setAutoCancel(true);

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = builder.getNotification();
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify((int) System.currentTimeMillis(), notification);
    }

    public static void showSync(final String message) {
        if (Main.context != null) {
            Main.context.viewHeader.syncIcon.setVisibility(View.VISIBLE);
            Main.context.statusMessage.setText(message);
            //Main.context.blockStatus.setVisibility(View.VISIBLE);
        }
    }

    public static void hideSync() {
        if (Main.context != null) {
            Main.context.viewHeader.syncIcon.setVisibility(View.GONE);
            Main.context.blockStatus.setVisibility(View.GONE);
        }
    }

    /////////////////////////


    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public boolean onFling(MotionEvent start, MotionEvent finish, float xVelocity, float yVelocity) {
        if (viewMode == VIEW_PROGNOSIS) {
            if (start.getRawX() > finish.getRawX()) {
                Calendar now = viewPeriod[0];
                now.add(Calendar.MONTH, 1);
                viewPeriod = getPeriod(Calendar.MONTH, now);
                viewPeriod[1].add(Calendar.DAY_OF_MONTH, getSharedPreferences(Main.PREFERENCES_NAME, 0).getInt("PROGNOSIS_DAYS_AFTER", 10));
                viewPrognosis.viewPeriod = viewPeriod;
                setMode(VIEW_PROGNOSIS);
            } else {
                Calendar now = viewPeriod[0];
                now.add(Calendar.MONTH, -1);
                viewPeriod = getPeriod(Calendar.MONTH, now);
                viewPeriod[1].add(Calendar.DAY_OF_MONTH, getSharedPreferences(Main.PREFERENCES_NAME, 0).getInt("PROGNOSIS_DAYS_AFTER", 10));
                viewPrognosis.viewPeriod = viewPeriod;
                setMode(VIEW_PROGNOSIS);
            }
        }
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public boolean onTouchEvent(MotionEvent me) {
        return gDetector.onTouchEvent(me);
    }
/////////////////////////


    class MyGestureDetector extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                //right to left
                if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    int featureWidth = root.getMeasuredWidth();
                    currentScrollItem = (currentScrollItem < (scrollItems.length - 1)) ? currentScrollItem + 1 : scrollItems.length - 1;
                    root.smoothScrollTo(currentScrollItem * featureWidth, 0);
                    return true;
                }
                //left to right
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    int featureWidth = root.getMeasuredWidth();
                    currentScrollItem = (currentScrollItem > 0) ? currentScrollItem - 1 : 0;
                    root.smoothScrollTo(currentScrollItem * featureWidth, 0);
                    return true;
                }
            } catch (Exception e) {
                Log.e("Fling", "There was an error processing the Fling event:" + e.getMessage());
            }
            return false;
        }
    }

    public static String getVersionName(Context context) {

        String versionName = null;
        try {
            versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (final PackageManager.NameNotFoundException e) {
            Log.e(context.getClass().getSimpleName(), "Could not get version from manifest.");
        }
        if (versionName == null) {
            versionName = "unknown";
        }
        return versionName;
    }


}